<?php

class WuZiKuController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new WuZiKu;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['WuZiKu']))
		{
			$model->attributes=$_POST['WuZiKu'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['WuZiKu']))
		{
			$model->attributes=$_POST['WuZiKu'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('WuZiKu');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new WuZiKu('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['WuZiKu']))
			$model->attributes=$_GET['WuZiKu'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return WuZiKu the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=WuZiKu::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param WuZiKu $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='wu-zi-ku-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 根据物资名称搜索物资库数据
	 */
	public function actionSearchByName()
	{
		// 将来是要根据name分词来实现搜索
		// $name = isset($_GET['name']) ? urldecode($_GET['name']) : '';
		// 现在先读取全部数据
		$name = '';
		
		$wuZiKus = WuZiKu::model()->findAll(array('condition' => 'name like \'%' . $name . '%\''));
		
		if(!$wuZiKus){
			echo 0;
			exit();
		}
		
		$retArr = array();
		$i = 0;
		
		foreach($wuZiKus as $wuZiKu)
		{
			$retArr[$i] = $wuZiKu->attributes;
			
			$retArr[$i]['name'] = urlencode($retArr[$i]['name']);
			
			$i++;
		}
		
		echo json_encode($retArr);
	}
	/**
	 * Lists all models.
	 */
	public function actionLoad()
	{
		$model = new Mobilefile;
		if(isset($_POST['Mobilefile'])){
			set_time_limit(1000);
			$model->attributes=$_POST['Mobilefile'];
			$file = CUploadedFile::getInstance($model, 'filePath');  
			if( is_object($file) && get_class($file) === 'CUploadedFile' ){
				Yii::app()->session['wuzi_name'] = $_POST['Mobilefile']['version'];
				$extensionName = strtolower($file->getExtensionName());
				$modelName = get_class($model);
				$timestamp = time()-1320937220;//为了防止浏览器缓存，使用时间戳作为版本号(减去一个整数，可以减小版本号)
				$fileName = $modelName.'-'.$timestamp.'.'.$extensionName;
			    $model->filePath = $fileName;  
			}  
			$model->addTime = new CDbExpression('NOW()');
			if($model->validate()){
				if( $model->save() ){  
				    if(is_object($file) && get_class($file) === 'CUploadedFile'){  
				        $file->saveAs(Yii::app()->basePath.'/../uploads/'.$model->filePath);  
				    	Yii::app()->session['wuzi_url'] = Yii::app()->basePath.'/../uploads/'.$model->filePath;
				    }  
				    $this->_wuzi(Yii::app()->session['wuzi_url']);//从excel导入mysql
				    $this->redirect(array('mobilefile/admin'));  
				}  
			}
		}
		
		exit("上传成功！");
		
	}
	
	/**
	 * 测试：indexTest
	 */
	public function actionUpExcel()
	{
		$model = new Mobilefile;
		$this->render('upexcel',array(
			'model'=>$model,
		));
	}
	
	
	/**
	 * 从excel导入mysql
	 */
	public function _wuzi($path_url)
	{
		$sheetArray = Yii::app()->yexcel->readActiveSheet($path_url);
		
		foreach($sheetArray as $k=>$row)
		{
			if($k==1)//不输出表头
				continue;
			//启用事务处理	
//			$transaction=Yii::app()->db->beginTransaction();
//			try
//			{	
				$modle = new WuZiKu;
				$modle->wuZiId=$row['A'];
				$modle->name=$row['B'];
				$modle->pinyin = WuZiKu::model()->returnPinyin($row['B']);
				$modle->detail=$row['C'];
				$modle->measure=$row['D'];
				$modle->price=$row['E'];
				$modle->source= Yii::app()->session['wuzi_name'];
				$modle->save(false);
//				$transaction->commit();
//			}
//			catch(Exception $e) // 如果有一条查询失败，则会抛出异常
//			{
//			    $transaction->rollBack();
//			}
			
		}
		$this->redirect(array('wuziku/admin'));
	}
	
}
